//
//  PhotoTool.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/17.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "PhotoTool.h"

#import "PhotoModel.h"

static PhotoTool *tool = nil;

@implementation PhotoTool

+ (instancetype)sharePhotoTool{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        tool = [[PhotoTool alloc] init];
    });
    
    return tool;
    
}


- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending{
    
    NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        PHAsset *asset = (PHAsset *)obj;
        [assets addObject:asset];
    }];
    
    return assets;
    
}

- (NSArray<PhotoAblumListModel *> *)getPhotoAblumList{
    
    
    NSMutableArray<PhotoAblumListModel *> *photoAblumList = [NSMutableArray array];
    
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    [smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //过滤掉视频和最近删除
        if (collection.assetCollectionSubtype != 202 && collection.assetCollectionSubtype < 212) {
            
            NSArray<PHAsset *> *assets = [self getAssetsInAssetCollection:collection ascending:NO];
            
            if (assets.count > 0) {
                
                PhotoAblumListModel *album = [[PhotoAblumListModel alloc] init];
                album.title = collection.localizedTitle;
                album.count = assets.count;
                album.headImageAsset = assets.firstObject;
                album.assetCollection = collection;
                
                [photoAblumList addObject:album];
                
            }
            
        }
        
    }];
    
    //获取用户创建的相册
    
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    
    [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *  _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
       
        NSArray<PHAsset *> *array = [self getAssetsInAssetCollection:collection ascending:NO];
        
        if (array.count > 0) {
            
            PhotoAblumListModel *model = [[PhotoAblumListModel alloc] init];
            
            model.title = collection.localizedTitle;
            model.count = array.count;
            model.assetCollection = collection;
            model.headImageAsset = array.firstObject;
            
            [photoAblumList addObject:model];
            
        }
        
        
    }];
    
    
    
    return photoAblumList;
}
        
#pragma mark ---获取指定相册内的所有图片

- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetaCollection ascending:(BOOL)ascending{
    
    NSMutableArray<PHAsset *> *array = [NSMutableArray array];
    
    PHFetchResult *result = [self fetchAssetsInAssetCollection:assetaCollection ascending:ascending];
    
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        if (((PHAsset *)obj).mediaType == PHAssetMediaTypeImage) {
            [array addObject:obj];
        }
        
    }];
    
    return array;
    
}

- (PHFetchResult *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending{
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
    
    return result;
}


#pragma mark 获取asset对应的图片

- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *, NSDictionary *))completion{
    
    static PHImageRequestID requestID = -1;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = MIN([UIScreen mainScreen].bounds.size.width, 500);
    
    if (requestID >= 1 && size.width / width == scale) {
        
        [[PHCachingImageManager defaultManager] cancelImageRequest:requestID];
    }
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    
    option.resizeMode = resizeMode;
    option.networkAccessAllowed = YES;
    
    requestID = [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
       
        BOOL downloadFinished = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey];
        
        if (downloadFinished && completion) {
            completion(image,info);
        }
        
    }];
    
}


- (void)requestImageForAsset:(PHAsset *)asset scale:(CGFloat)scale resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *))completion{
    
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = resizeMode;
    option.networkAccessAllowed = YES;
    
    [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
       
        BOOL downloadFinished = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];
        
        if (downloadFinished && completion) {
            
            CGFloat scal = imageData.length/  (CGFloat)UIImageJPEGRepresentation([UIImage imageWithData:imageData], 1).length;
            NSData *data = UIImageJPEGRepresentation([UIImage imageWithData:imageData], scale == 1 ? scal : scal / 2);
            completion([UIImage imageWithData:data]);
            
        }
        
    }];
    
}


#pragma mark 保存图片到相册

- (void)saveImageToAblum:(UIImage *)image completion:(void (^)(BOOL, PHAsset *))completion{
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusDenied) {
        if (completion) {
            completion(NO,nil);
        }
    } else if (status == PHAuthorizationStatusRestricted) {
        
        if (completion) {
            completion(NO,nil);
        }
    } else {
        
        __block NSString *assetId = nil;
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            
            assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
           
            if (!success) {
                
                if (completion) {
                    completion(NO, nil);
                    return ;
                }
                
            }
            
//            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].lastObject;
            
//            PHAssetCollection *desCollection = [self ge]
            
        }];
        
    }
}

#pragma mark 获取自定义相册

- (PHAssetCollection *)getDestinationCollection{
    
    PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (PHAssetCollection *collection in collectionResult) {
        
        ;
        if ([collection.localizedTitle isEqualToString:[[NSBundle mainBundle].infoDictionary valueForKey:(__bridge NSString *)kCFBundleNameKey]]) {
            
            return collection;
        }
        
    }
    
    //新建自定义相册
    
    __block NSString *collectionId = nil;
    
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:[[NSBundle mainBundle].infoDictionary valueForKey:(__bridge NSString *)kCFBundleNameKey]].placeholderForCreatedAssetCollection.localIdentifier;
        
    } error:&error];
    
    if (error) {
        
        return nil;
    }
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
    
    
}

- (BOOL)judgeAssetisInLocalAblum:(PHAsset *)asset{
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.networkAccessAllowed = NO;
    option.synchronous = YES;
    
    __block BOOL isInLocalAblum = YES;
    
    [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
       
        isInLocalAblum = imageData ? YES : NO;
        
    }];
    
    return isInLocalAblum;
}

- (void)getPhotoBytesWithArray:(NSArray *)photos completion:(void (^)(NSString *))completion{
    
    __block NSInteger dataLength = 0;
    __block NSInteger count = photos.count;
    
    __weak typeof(self) weakself = self;
    for (int i = 0; i < photos.count; i++) {
        
        PhotoModel *model = photos[i];
        [[PHCachingImageManager defaultManager] requestImageDataForAsset:model.asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
           
            dataLength += imageData.length;
            count--;
            
            if (count <= 0) {
                
                if (completion) {
                    completion([weakself transformDataLength:dataLength]);
                }
            }
            
        }];
        
    }
    
}

- (NSString *)transformDataLength:(NSInteger)dataLength{
    
    NSString *bytes = @"";
    if (dataLength >= 0.1 * (1024 * 1024)) {
        bytes = [NSString stringWithFormat:@"%.1fM",dataLength/1024/1024.0];
    } else if (dataLength >= 1024) {
        
        bytes = [NSString stringWithFormat:@"%.0fK",dataLength/1024.0];
    } else {
        
        bytes = [NSString stringWithFormat:@"%zdB",dataLength];
    }
    
    return bytes;
    
}


@end
